<?php
class sfGraduaActions extends sfActions
{
  protected $msgServiceExceptionPrefix = '[ServiceException]';

  /**
   * @return JsCall
   * @param
   *       $e parametro da exception
   *       $jsCall objeto do tipo JsCall
   *       $fields array de campos
   *       $fieldIdPrefix prefixo do campo que o correu o erro
   *       $rethrow caso ainda reste algum erro ele � mostrado
   *       $jsControler arquivo JavaScript de controle
   */
  function transferErrorsToCall(ServiceValidationException $e, JsCall $jsCall, $fields,
  $fieldIdPrefix, $rethrow,$jsController = 'UtilC') {
    foreach($e->getErrors() as $k=>$error) {
      if(in_array($error['property'],$fields)) {
        $jsCall->addCommand($jsController,'showFormError')
        ->addPHPParam('fieldName',$fieldIdPrefix.'-'.$error['property'])
        ->addPHPParam('message',$error['message']);
        $e->removeError($k);
      }
    }
    if($rethrow && $e->hasError()) {
      $e->setJsCall($jsCall);
      throw $e;
    }
  }
  /**
   * Fuuçãoo utilizada para criar um objeto com dados vindos de uma requisi��o
   *
   * @param Recebe o prefixo do campo ex.: essay de essay[file]
   * @return retorna um objeto do tipo StdClass
   */
   function getObjRequest($parameterName,$arCheckbox = array()) {
		$obj = new StdClass;
		foreach( $this->getRequestParameter($parameterName) as $i=>$j ) {
			if(array_search($i,$arCheckbox) !== false) {
			  $p = array_search($i,$arCheckbox);
			  unset($arCheckbox[$p]);
			  $obj->$i = true;
			}
			else {
			  $obj->$i = $j;
			}
		}
		foreach($arCheckbox as $falseValue) {
		  $obj->$falseValue = false;
		}
		return $obj;
	}

  /**
   * IMPORTANTE: esse método deve ser usado na action com return, ex: return $this->showJsCall(...
   * Chama JsCall->toJson e coloca o resultado no response.
   * 
   * @param JsCall $jsCall
   * @return SfView::NONE
   */
  function showJsCall(JsCall $jsCall) {
    $response = $this->getResponse();
    $response->setContent($jsCall->toJson());
    return sfView::NONE;
  }
  
  function execInBackground($cmd) {
    if (substr(php_uname(), 0, 7) == "Windows"){
        pclose(popen("start /B ". $cmd, "r")); 
    }
    else {
        exec($cmd . " > /dev/null &");  
    }
  }

  public function openOnIde($filepath = null) {
    if(!$filepath) {
        $class = get_class($this);
        $ref = new ReflectionClass($class);
        $filepath = $ref->getFileName();
    }
    $cmd = 'C:\"Program Files"\"NetBeans 6.5.1"\bin\netbeans.exe --open "%s"';
    $cmd = sprintf(
        $cmd,
        $filepath
    );

    if (substr(php_uname(), 0, 7) == "Windows"){
        pclose(popen("start /B ". $cmd, "r"));
    }
    else {
        exec($cmd . " > /dev/null &");
    }
  }

  /**
   * @return JsCall
   */
  public function getResponseJsCall() {
      return $this->getResponse()->getJsCallReference();
  }
}
?>